package me.ezjs.framework.core.model;

import me.ezjs.framework.config.SpringContextUtil;
import me.ezjs.framework.config.ZeroConfig;

/**
 * Created by zero-mac on 16/3/10.
 */
public class OperateUtil {
    protected final static String ESCAPE = " escape '\\'";//区分mysql和oracle数据库


    public final static String buildOperateClause(Parameter p) {
        StringBuffer hqlBuilder = new StringBuffer();
        String bind = p.getBindName();
        String aliasKey = p.getAliasKey();

        switch (p.getOperate()) {
            case ISNULL:
            case NOTNULL:
                hqlBuilder.append(aliasKey);
                hqlBuilder.append(p.getOperate().getSql());
                break;
            case EQUAL:
            case NOTEQUAL:
            case LESS:
            case LESSEQUAL:
            case GREAT:
            case GREATEQUAL:
                hqlBuilder.append(aliasKey);
                hqlBuilder.append(p.getOperate().getSql());
                hqlBuilder.append(':').append(bind);
                break;
            case LIKE:
                hqlBuilder.append(aliasKey);
                hqlBuilder.append(p.getOperate().getSql());
                hqlBuilder.append(':').append(bind);
                if (ZeroConfig.isEscapeSlash()) {
                    hqlBuilder.append(ESCAPE);
                }
                break;
            case LOWERLIKE:
                hqlBuilder.append("lower(" + aliasKey + ")");
                hqlBuilder.append(p.getOperate().getSql());
                hqlBuilder.append(':').append(bind);
                if (ZeroConfig.isEscapeSlash()) {
                    hqlBuilder.append(ESCAPE);
                }
                break;
            case BETWEEN:
                hqlBuilder.append(aliasKey);
                hqlBuilder.append(p.getOperate().getSql());
                hqlBuilder.append(':').append(bind).append("lo").append(" and ");
                hqlBuilder.append(":").append(bind).append("hi");
                break;
            case IN:
            case NOTIN:
                hqlBuilder.append(aliasKey);
                hqlBuilder.append(p.getOperate().getSql());
                hqlBuilder.append("(:").append(bind).append(')');
                break;
            default: // impossible
                break;
        }

        return hqlBuilder.toString();
    }
}
